import 'dart:async';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/controller/app_package_info_getx_controller.dart';
import 'package:star_author/env/env_config.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rouces_util.dart';

import 'package:star_author/utils/toast_util.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/websocket_manage/websocket_manage.dart';
import 'package:star_author/views/login/phone_login.dart';
import 'package:star_author/views/stream/local_video_page.dart';
import 'package:star_author/views/stream/open_live.dart';
import 'package:star_author/widgets/alert.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:dio_log/http_log_list_widget.dart';
import 'package:draggable_widget/draggable_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../../utils/http/api_manager.dart';
import '../../utils/http/http_util.dart';
import '../../utils/rong_im/rong_im.dart';

class NewUiHomePage extends StatefulWidget {
  const NewUiHomePage({Key? key}) : super(key: key);

  @override
  State<NewUiHomePage> createState() => _NewUiHomePageState();
}

class _NewUiHomePageState extends State<NewUiHomePage> {
  late StreamSubscription loginStatusSubscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initConfigProviderData();
    initVersion();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      if (UserUtil.isLogin(Get.context!)) {
        initUser();
      } else {
        Get.to(PhoneLoginPage());
      }
      if (!EnvConfig.isProd()) {
        WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
          _insertOverlay(context);
        });
      }
    });
    loginStatusSubscription =
        GlobalEventBus().bus.on<UserLoginEvent>().listen((event) {
      if (event.isLogin) {
        initUser();
        setState(() {});
      }
    });
  }

  void _insertOverlay(BuildContext context) {
    return Overlay.of(context)?.insert(
      OverlayEntry(builder: (context) {
        final size = MediaQuery.of(context).size;
        return DraggableWidget(
          bottomMargin: 60,
          topMargin: 60,
          intialVisibility: true,
          horizontalSpace: 20,
          shadowBorderRadius: 20,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Get.to(HttpLogListWidget());
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.1),
                borderRadius: BorderRadius.circular(100),
              ),
              width: 36,
              height: 36,
              child: Text(
                "http",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
          initialPosition: AnchoringPosition.bottomLeft,
        );
      }),
    );
  }

  initUser() {
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "scene": "happ-${Get.currentRoute}",
      },
    ).then((value) {
      Provider.of<UserProvider>(context, listen: false)
          .set(key: 'userInfo', value: value.data);
      WebSocketManage().initWebSocket();
      setState(() {});
    });
  }

  List list = [
    {
      'icon': "ic_manager_lt",
      'title': "本地视频管理",
    },
    {'icon': "ic_upload_log_lt", 'title': "上传日志"},
    {'icon': "ic_close_lt", 'title': "关闭直播间"},
  ];

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    loginStatusSubscription.cancel();
  }

  initVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //版本名
    version = packageInfo.version;
    if (mounted) setState(() {});
  }

  String version = "";

  @override
  Widget build(BuildContext context) {
    bool is_login = UserUtil.isLogin(context);
    UserProvider provider = Provider.of<UserProvider>(context, listen: false);
    int id = 0;
    String cover = "";
    String name = "首页";
    bool isAnchor = false;
    String anchor_changed_at = "";
    if (provider.user!['id'] != 0) {
      //登录
      List maintain_studios = provider.user!['maintain_studios'] ?? [];
      if (maintain_studios.length > 0) {
        id = maintain_studios[0]['id'] ?? 0;
        cover = maintain_studios[0]['vertical_cover'] ?? "";
        name = maintain_studios[0]['name'] ?? "";
        anchor_changed_at = maintain_studios[0]['anchor_changed_at'] ?? "";
        isAnchor = true;
      }
    }
    //主播信息
    Map? anchor = provider.user?['anchor'] ?? {};
    bool isAnchorAccount = false;
    if (anchor?.isNotEmpty ?? false) {
      isAnchorAccount = true;
    }
    return Scaffold(
      body: Stack(
        children: [
          //背景渐变
          Container(
            child: Image.asset(
              RoucesUtil.getAssets('bg_anchor_lt'),
            ),
          ),
          Container(
            padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top + 32.w,
              left: 16.w,
              right: 16.w,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  '主播端',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w900,
                  ),
                ),
                SizedBox(
                  height: 4.w,
                ),
                Text(
                  '版本号V$version',
                  style: TextStyle(
                    color: Color(0xFF969798),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(
                  height: 20.w,
                ),
                Container(
                  width: Get.width,
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(
                          top: 20.w,
                          left: 16.w,
                        ),
                        child: Row(
                          children: [
                            buildCircleCover(cover: cover, size: 55.w),
                            SizedBox(
                              width: 8.w,
                            ),
                            Container(
                              height: 55.w,
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    '${name}',
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 18.sp,
                                      fontFamily: 'PingFang HK',
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  Opacity(
                                    opacity: 0.60,
                                    child: Text(
                                      '上次直播：${DateUtil.formatDateStr(anchor_changed_at, format: 'yyyy/MM/dd HH:mm:ss')}',
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 12.sp,
                                        fontFamily: 'PingFang HK',
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            GestureDetector(
                              child: Container(
                                alignment: Alignment.center,
                                width: 72.w,
                                height: 29.w,
                                child: Text(
                                  is_login ? '退出登录' : "去登录",
                                  style: TextStyle(
                                    color: Color(0xFF9C7F2D),
                                    fontSize: 12.sp,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                                decoration: ShapeDecoration(
                                  color: Color(0xFFFFE495),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(14.50),
                                  ),
                                ),
                              ),
                              onTap: () {
                                if (!is_login) {
                                  Get.to(PhoneLoginPage());
                                } else {
                                  onLoggedOut();
                                }
                              },
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20.w,
                      ),
                      if (is_login)
                        Container(
                          margin: EdgeInsets.symmetric(
                            horizontal: 8.w,
                          ),
                          width: Get.width,
                          child: ListView.separated(
                            itemBuilder: (context, index) {
                              return buildRow(list[index]['icon'],
                                  list[index]['title'], index, id);
                            },
                            separatorBuilder: (context, index) {
                              return buildDriver();
                            },
                            itemCount: list.length,
                            shrinkWrap: true,
                            padding: EdgeInsets.zero,
                          ),
                          decoration: ShapeDecoration(
                            color: Colors.white,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.w)),
                          ),
                        ),
                      SizedBox(
                        height: 8.w,
                      ),
                    ],
                  ),
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(-0.33, -0.94),
                      end: Alignment(0.33, 0.94),
                      colors: [Color(0xFFFFD149), Color(0xFFFFEAAC)],
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: GestureDetector(
        child: Container(
          margin: EdgeInsets.only(
            bottom: 20.w,
          ),
          child: is_login
              ? Image.asset(
                  RoucesUtil.getAssets('ic_to_live_lt'),
                  width: 95.w,
                  height: 102.w,
                )
              : Container(
                  height: 1,
                ),
        ),
        onTap: () {
          toOpenLive();
        },
        behavior: HitTestBehavior.opaque,
      ),
    );
  }

  ///退出登陆
  void onLoggedOut() {
    Alert.showCustomDialog(
        Container(
          child: Text(
            '确定要退出登录吗？',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.normal,
              decoration: TextDecoration.none,
              fontSize: 16.sp,
              color: ColorConf.normal,
            ),
          ),
        ),
        context,
        confirmText: '确认登出', onConfirm: () async {
      final user = Provider.of<UserProvider>(context, listen: false);

      user.clearToken();
      RongUtil.disconnect();
      setState(() {});

      ///断开ws
      LogUtil.v('WebSocketManage WebSocket连接关闭 - setting');
      WebSocketManage().closeSocket();
    });
  }

  toOpenLive() {
    //判断是否登录
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: false,
      isErrorToast: false,
    ).then((value) async {
      Provider.of<UserProvider>(context, listen: false)
          .set(key: 'userInfo', value: value.data);
      Map<Permission, PermissionStatus> map = await _initPermission();
      if (map[Permission.camera] == PermissionStatus.granted &&
          map[Permission.microphone] == PermissionStatus.granted &&
          map[Permission.storage] == PermissionStatus.granted) {
        List maintain_studios = value.data?['maintain_studios'] ?? [];
        if (maintain_studios.length > 0) {
          bool _switch = maintain_studios[0]['switch'] ?? false;
          bool visible = maintain_studios[0]['visible'] ?? false;
          if (_switch) {
            ToastUtil.show("当前直播间有人在播，请稍后再试");
            return;
          }
          if (!visible) {
            ToastUtil.show("当前直播间已被撤销，不能开播!");
            return;
          }
          Get.to(OpenLive());
        } else {
          ToastUtil.show("当前用户没有直播间");
        }
      } else if (map[Permission.camera] == PermissionStatus.permanentlyDenied) {
        CustomToast.show("摄像头权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else if (map[Permission.microphone] ==
          PermissionStatus.permanentlyDenied) {
        CustomToast.show("麦克风权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else if (map[Permission.storage] ==
          PermissionStatus.permanentlyDenied) {
        CustomToast.show("文件读写权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else {
        _initPermission();
      }
    });
  }

  Future _initPermission() {
    return [Permission.camera, Permission.microphone, Permission.storage]
        .request();
  }

  buildDriver() {
    return Container(
      width: Get.width * 0.6,
      height: 0.50.w,
      decoration: BoxDecoration(color: Color(0xFFEEEEEE)),
    );
  }

  buildRow(String icon, String title, int index, id) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Image.asset(
                  RoucesUtil.getAssets(icon),
                  width: 24.w,
                  height: 24.w,
                ),
                SizedBox(
                  width: 12.w,
                ),
                Text(
                  title,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 16.sp,
                    fontFamily: 'PingFang HK',
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            Image.asset(
              RoucesUtil.getAssets('ic_right_arrow2_lt'),
              width: 24.w,
              height: 24.w,
            ),
          ],
        ),
        height: 64.w,
        alignment: Alignment.centerLeft,
      ),
      onTap: () {
        onClick(index, id);
      },
    );
  }

  onClick(index, id) {
    switch (index) {
      case 0:
        Get.to(LocalVideoPage());
        break;
      case 1:
        MediaRecorderUtil.uploadLogLogFile();
        break;
      case 2:
        //判断是否登录
        HttpUtil.commonRequest(
          context,
          '/api/v1/studios/${id}/close',
          method: HttpUtil.MethodPost,
        ).then((value) {
          CustomToast.show("关闭直播间成功");
        });
        break;
    }
  }

  void initConfigProviderData() async {
    PackageInfo? packageInfo =
        Get.find<AppPackageInfoGetXController>().packageInfo;
    String localVersion = packageInfo?.version ?? "";
    dynamic settingsRes = await HttpUtil.commonRequest(
      Get.context!,
      ApiManager.settings,
      queryParameters: {
        "app_version": localVersion,
      },
      isLoading: false,
      isErrorToast: false,
    );
    if (settingsRes.data != null) {
      IndexPageHandler.setAppConfig(settingsRes.data);

      ///融云聊天室
      await RongUtil.init();
    }
    if (UserUtil.isLogin(context)) {
    }
  }
}

class IndexPageHandler {
  static void setAppConfig(Map data) {
    Provider.of<ConfigProvider>(Get.context!, listen: false)
        .set(key: "settings", value: data);

    RongUtil.AppKey = data['rong_cloud_app_key'] ?? "y745wfm8y5e2v";
    App.appTitle = data["app_homepage_title"] ?? "闲置玉翠交易平台";
    App.shipped_time_description = data["shipped_time_description"] ?? "";
    App.gold_deducting_price = (double.parse(
        data["gold_deducting_price_for_classify"]['gold_ornament'].toString()));
    App.gold_deducting_price_for_classify =
        data["gold_deducting_price_for_classify"] ?? App.defaultClassify;
    App.wechat_gold_service_url = data["wechat_gold_service_url"] ?? "";
    App.popover_wait_time = data["popover_wait_time"] ?? 3;
    App.seconds_for_copy_clipboard = data["seconds_for_copy_clipboard"] ?? 60;
    App.wechat_appraise_service_url = data["wechat_appraise_service_url"] ?? "";
    StreamConf.PullBaseUrl =
        data['pull_base_url'] ?? StreamConf.PullBaseUrlDefault;
    StreamConf.PushBaseUrl =
        data['push_base_url'] ?? StreamConf.PushBaseUrlDefault;
    App.customerServiceUrl = data['wechat_service_url'] ??
        "https://work.weixin.qq.com/kfid/kfcfbc1ace60b3fa7b9";
    App.complaintsServiceUrl = data['wechat_complain_url'] ??
        "https://work.weixin.qq.com/kfid/kfc40ba31340078782d";

    App.universalLink = data['wechat_app_login_url'] ?? App.universalLink;
  }
}
